var ObjectID = require('mongodb').ObjectID;

MongoRepo = function(db) {
   console.log("Mongodb Repository is activated!");
   this.db = db;
};

MongoRepo.prototype.getCollection = function(collectionName, callback) {
   this.db.collection(collectionName, function(error, the_collection) {  
      if( error ) callback(error);
      else        callback(null, the_collection);
  });
};

MongoRepo.prototype.findAll = function(collectionName, callback) {
   this.getCollection(collectionName, function(error, the_collection) {
      if( error ) callback(error);
      else {
         the_collection.find().toArray(function(error, results) {
            if( error ) callback(error);
            else        callback(null, results);
         });
      }
   });
};

MongoRepo.prototype.get = function(collectionName, id, callback) {
   console.log("get");
   this.getCollection(collectionName, function(error, the_collection) {
      if (error) callback(error);
      else {
         var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
         if (!checkForHexRegExp.test(id)) callback({error: "invalid id"});
         else the_collection.findOne({'_id':ObjectID(id)}, function(error,doc) {
            if (error)  callback(error);
            else        callback(null, doc);
         });
      }
   });
};


MongoRepo.prototype.save = function(collectionName, obj, callback) {
   console.log("save");
   this.getCollection(collectionName, function(error, the_collection) {
      if( error ) callback(error)
      else {
         obj.created_at = new Date();
         the_collection.insert(obj, function() {
            callback(null, obj);
         });
      }  
   });
};

MongoRepo.prototype.update = function(collectionName,id, obj, callback) {
   console.log("update");
   this.getCollection(collectionName, function(error, the_collection) {
      if( error ) callback(error)
      else {
         delete obj['_id']
         the_collection.update({_id: ObjectID(id)}, obj, function() {
            callback(null, obj);
         });
      }
   });
};

MongoRepo.prototype.del = function(collectionName, id, callback) {
   console.log("delete");
   this.getCollection(collectionName, function(error, the_collection) {
      if( error ) callback(error)
      else {
         the_collection.remove({_id: ObjectID(id)}, function(err, doc) {
            if (error)  callback(error);
            else        callback(null, doc);
         });
      }
   });
};


exports.MongoRepo = MongoRepo;
